/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util;

import java.math.BigDecimal;

import com.enfry.common.util.validate.Validates;

/**
 * 
 * 整型相关工具类
 * 
 * @Title com.enfry.util.Ints
 * @author Penghu
 * @date 2016年11月22日
 */
public class Ints {
	/** 字符串转换为int,异常不处理 注:默认10进制 */
	public static int toInt(String s) {
		return Integer.parseInt(s);
	}

	/** 字符串转换为int 如果异常则返回缺省值 */
	public static int toInt(String s, int defaultValue) {
		if (!Validates.isInteger(s))
			return defaultValue;

		try {
			return Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	/** 对象转换为int 如果异常则返回缺省值 */
	public static int toInt(Object o, int defaultValue) {
		if (o == null)
			return defaultValue;
		else if (o instanceof Integer)
			return (Integer) o;
		else if (o instanceof Long)
			return (int) ((long) (Long) o);
		else if (o instanceof String)
			return toInt((String) o, defaultValue);
		else if (o instanceof BigDecimal)
			return toInt(o.toString(), defaultValue);
		else
			return defaultValue;
	}

	public static int length(int i) {
		boolean isNegative = false;
		if (i < 0) {
			i = -i;
			isNegative = true;
		}

		int len = String.valueOf(i).length();
		return isNegative ? len + 1 : len;
	}

	public static int getMaxInt(int length) {
		if (length >= 10)
			return 0x7FFFFFFF;

		if (length <= 0)
			return 9;

		String maxString = "999999999".substring(0, length);
		return toInt(maxString);
	}
}
